<template>
	<base-wrapper activeTabName="index">
		<view class="IndexTitleBox">
			<view style="width: 49%">
				<up-copy :content="title">
					<up-button class="custom-style" color="#1e293b" text="复制文案"></up-button>
				</up-copy>
			</view>
			<view style="width: 49%">
				<up-button class="custom-style" color="#475569" text="保存图片" @click.stop="downForque"></up-button>
			</view>
		</view>
		<view class="wrap">
			<up-waterfall v-model="flowListImg">
				<template v-slot:left="{ leftList }">
					<view class="demo-warter" v-for="(item, index) in leftList" :key="index">
						<!-- 警告：微信小程序中需要hx2.8.11版本才支持在template中结合其他组件，比如下方的lazy-load组件 -->
						<up-lazy-load threshold="-450" border-radius="10" :image="item" :index="index"></up-lazy-load>
						<view class="demo-title">
							<up-copy :content="item">
								<text>点击复制</text>
							</up-copy>
							<span @click.stop="imgDownload(item)">下载图片</span>
						</view>
					</view>
				</template>
				<template v-slot:right="{ rightList }">
					<view class="demo-warter" v-for="(item, index) in rightList" :key="index">
						<up-lazy-load threshold="-450" border-radius="10" :image="item" :index="index"></up-lazy-load>
						<view class="demo-title">
							<up-copy :content="item">
								<text>点击复制</text>
							</up-copy>
							<span @click.stop="imgDownload(item)">下载图片</span>
						</view>
					</view>
				</template>
			</up-waterfall>
		</view>
	</base-wrapper>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { getUserTask } from '@/api/subscribe_task.js';
import { useUserInfo } from '@/stores/userInfo.js';

const userStore = useUserInfo();

onMounted(async () => {
	// console.log("小程序初始化挂载,进入素材入口页面(material.vue)!");
	// console.log('正在初始化用户数据...');

  //用户没有登录就进行登录操作
  if(userStore.userData.wxopenid === null || userStore.userData.wxopenid === '') {
    uni.showLoading({title: "登录中...", mask: true});
    await userStore.initUser();
    if (userStore.userData.wxopenid != null && userStore.userData.wxopenid.length > 16) {

      uni.showToast({title: "登录成功!", icon: 'success'});
    }
  }
  console.log("用户信息",userStore.userData);
  uni.hideLoading();

  uni.showLoading({title: "刷新数据中...", mask: true});
  await userStore.updateUserData(userStore.userData.wxopenid);
  uni.hideLoading();
  uni.showToast({title: "刷新成功!", icon: 'success'});

  if (userStore.userData.wxopenid != null && userStore.userData.wxopenid.length > 16){
    getUserMaterialDownload();
  }

});

let flowListImg = ref([]);
let title = ref();
let userTaskUrls = ref([]);
let userTaskIndex = ref();

let getUserMaterialDownload = async () => {
	let res = await getUserTask({
		wxopenid: userStore.userData.wxopenid,
	});
	if (res.success) {
		userTaskUrls.value = res.data.urls;
		userTaskIndex.value = res.data.index;
		// console.log("用户素材打卡链接列表:" , userTaskUrls.value);
		// console.log("用户任务进度索引 : " , userTaskIndex.value);
		uni.showToast({ icon: 'loading', title: '加载素材中..', mask: true, duration: 3000 });

    if(true){
		  parseUserTaskImageList();
    }else{
      console.log("当前正处于开发模式,不进行素材链接解析显示...");
      setTimeout(()=>{uni.hideLoading();uni.$u.toast('获取素材任务成功!');},1500);
    }

	}
};

const parseUserTaskImageList = async () => {
	let key = '3maVcpIKvDRStAxDPqM1RUKMmE';
	//let url = 'http://xhslink.com/a/y8R0xpq6uN8Y';
	let url = userTaskUrls.value[userTaskIndex.value];

	if (url == null || url === '') {
		//记得在页面中间显示一个当前无任务....

		// console.error("当前任务进度索引下链接为空! 等待分配任务...");
		uni.hideLoading();
		uni.$u.toast('当前无任务!');
		return;
	}

	axios.get(`https://api.ip13.com/api/remark2/index?key=${key}&url=${url}`).then((res) => {
    console.log(res);
		if (res.data.code === 200) {
			flowListImg.value = res.data.data.images;
			title.value = res.data.data.title;
			uni.$u.toast('获取素材任务成功!');
		} else {
			uni.$u.toast('获取失败');
		}
	});

	uni.hideLoading();
};

let downForque = () => {
	let promise = Promise.resolve();
	flowListImg.value.forEach((url, index) => {
		console.log(url, index);
		promise = promise.then(() => {
			return download(url, index);
		});
	});
	return promise;
};

let download = (url, index) => {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url: url,
			success: (res) => {
				if (res.statusCode === 200) {
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: function (res) {
							uni.showLoading({
								title: '下载中(' + (index + 1) + '/' + flowListImg.value.length + ')',
							});
							if (index + 1 === flowListImg.value.length) {
								uni.$u.toast('下载成功');
								uni.hideLoading();
							}
							resolve(res);
						},
						fail: function (err) {
							reject(res);
						},
					});
				}
			},
			fail: function (err) {
				reject(err);
			},
		});
	});
};

let imgDownload = (url) => {
	uni.downloadFile({
		url: url,
		success: (res) => {
			if (res.statusCode === 200) {
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success: function (data) {
						uni.$u.toast('下载成功');
					},
					fail: function () {
						uni.$u.toast('下载失败');
					},
				});
			}
		},
	});
};

// let imgDownload = (url) => {
// 	console.log(url);
// 	uni.downloadFile({
// 		url: url,
// 		success: (res) => {
// 			if (res.statusCode === 200) {
// 				console.log(res);
// 				uni.saveImageToPhotosAlbum({
// 					filePath: res.tempFilePath,
// 					success: function (data) {
// 						uni.$u.toast('下载成功');
// 					},
// 				});
// 			}
// 		},
// 	});
/** else {
	return new Promise((resolve, reject) => {
	uni.downloadFile({
		url: flowListImg.value[i],
		success: (res) => {
			if (res.statusCode === 200) {
				console.log('下载成功', flowListImg.value[i]);
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success: function (res) {
					  wx.showLoading({
						title: '下载中(' + (index + 1) + '/' + flowListImg.value.length + ')'
					  })
					  resolve(res)
					},
					fail: function (err) {
					  reject(res)
					}
				});
			}
		},
		fail: function (err) {
		  reject(err)
		}
	});
		for (let i = 0; i < flowListImg.value.length; i++) {}
	} */
// };
</script>
<style lang="scss" scoped>
.IndexTitleBox {
	padding: 10rpx;
	display: flex;
	justify-content: space-around;
}

:deep(.u-button--square.data-v-461e713c) {
	border-radius: 10px;
}

.demo-warter {
	border-radius: 8rpx;
	background-color: #ffffff;
	padding: 10rpx;
}

.wrap {
	.demo-image {
		width: 100%;
		border-radius: 10rpx;
	}

	.demo-title {
		display: flex;
		justify-content: space-between;
		font-size: 30rpx;
		margin: 10rpx 0;
	}
}
</style>
